﻿using net_path.CSM.Common;
using net_path.Tools.Password;
using SanlieHash.BlockCipher;
using SanlieHash.GuoMi;
using SanlieHash.SecureHash;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;

namespace FileSC.WEBService.Plugins
{
    internal class TestPlug : PluginBase, IHttpPlugin
    {
        public async Task OnHttpRequest(IHttpSessionClient client, HttpContextEventArgs e)
        {
            var request = e.Context.Request;//http请求体
            var response = e.Context.Response;//http响应体
            response.Headers.Add(HttpHeaders.Server, HttpCommon.SERVER);
            response.Headers.Add(HttpCommon.AUTH_FW, PassGen.MakePassword(7));

            if (request.UrlEquals("/favicon.ico"))
            {
                await response.SetStatus(200, "")
                    .FromFileAsync(new FileInfo("./favicon.ico"), autoGzip :false);
                return;
            }

            if (request.IsGet() && request.UrlEquals("/say-hi"))
            {
                //直接响应文字
                await response
                        .SetStatus(200, "success")
                        .FromText("Success")
                        .AnswerAsync();//直接回应
                Console.WriteLine("处理/success");
                return;
            }
            //无法处理，调用下一个插件
            await e.InvokeNext();
        }

        internal static string MakeRegCode(byte[] key, string code)
        {
            var sm3 = new SM3();
            var sha512 = new SHA3_512();
            var guid = Guid.NewGuid().ToByteArray();
            var buf = new byte[4];
            key.CopyTo(buf, 0);
            var ss = SanlieHash.Helper.ToHexString(buf);
            var buf2 = System.Text.Encoding.UTF8.GetBytes(code);
            Array.Resize(ref buf, buf2.Length + 4);
            buf2.CopyTo(buf, 4);
            return ss + sm3.Make(buf) + sha512.Make(buf);
        }
        public static byte[] ToBytes(string hexstring)
        {
            var buf = new byte[hexstring.Length >> 1];
            for (var i = 0; i < buf.Length; i++) buf[i] = byte.Parse(hexstring.Substring(i << 1, 2), System.Globalization.NumberStyles.HexNumber);
            return buf;
        }

        public static string MakePwdCode(string pwd, string mypwd, string tag, string pre)
        {
            var code = SanlieHash.Helper.ToHexString(AES.EncryptBytes(mypwd, AES.EncryptBytes(tag, System.Text.Encoding.UTF8.GetBytes(pre + pwd))));
            return $"{tag}/{code}/{pre}";
        }
    }
}
